﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Xml.Serialization;

namespace XRM.Security.WebUI.Helpers
{
    public class Utils
    {
        public static void CreateOrClearDirectory(string dir)
        {
            if (Directory.Exists(dir))
            {
                string[] files = Directory.GetFiles(dir);

                foreach (string file in files)
                {
                    try
                    {
                        System.IO.File.SetAttributes(file, FileAttributes.Normal);
                        System.IO.File.Delete(file);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            else
            {
                Directory.CreateDirectory(dir);
            }
        }

        public static string GetSafeFileName(string path, string baseName)
        {
            string result = baseName;
            
            int i = 0;
            while (File.Exists(Path.Combine(path, result)))
            {
                ++i;
                result = Path.GetFileNameWithoutExtension(baseName) + " " + i.ToString() + Path.GetExtension(baseName);
            }
            return result;
        }

        public static string PrepareStringToJS(string value)
        {
            if (value == null)
                return null;

            return value.Replace("\\", "\\\\").Replace("'", "\\'");
        }

        public static string FirstLetterToUpper(string str)
        {
            if (str == null)
                return null;

            if (str.Length > 1)
                return char.ToUpper(str[0]) + str.Substring(1);

            return str.ToUpper();
        }

        public static string SerializeToString<T> (T obj)
        {
            var xmlSerializer = new XmlSerializer( obj.GetType() );
            using ( var textWriter = new StringWriter() )
            {
                xmlSerializer.Serialize( textWriter, obj );
                return textWriter.ToString();
            }
        }

        public static string GetPhisicalPath( string path )
        {
            return Path.Combine( AppDomain.CurrentDomain.BaseDirectory, path );
        }
    }

    public class ListItem
    {
        public string Text { get; set; }
        public string Value { get; set; }
    }
}